'''
Created on Jul 4, 2011

@author: pau <boemianrapsodi@gmail.com>
'''

import socket;

class Server:
    serverSocket=None;
    bufferSize=1024;
    
    def __init__(self, serverHost, serverPort):
        self.serverSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM);
        completeAddress = (serverHost, serverPort);
        self.serverSocket.bind(completeAddress);
        print "Server Initialized!";
    
    
    def ReceiveCommand(self):
        command,clientAddress = self.serverSocket.recvfrom(self.bufferSize);
        print "\nReceived %s from %s" % (command, clientAddress);
        
        return (command,clientAddress);
    
    def Respond(self, message, host):
        sendingSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM);
        data = bytes(message);
        sendingSocket.sendto(data,host);
        sendingSocket.close();
        print "I've sent %s to %s on port %s" % (message, host[0], host[1]); 
        
    def SendAFile(self, destinationAddress, fileToSend):
        dataSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
        try:
            dataSocket.connect((destinationAddress, 9090));
        except Exception, error:
            print "ERROR: Client not ready\n%s" % (error);
            exit();

        rawFile = open(fileToSend, "rb");
        rawData = rawFile.read();
        rawFile.close();

        print "Sending file %s to %s" % (fileToSend, destinationAddress);
        dataSocket.send(rawData);
        dataSocket.close();
        
    
    def CloseSocket(self):
        self.serverSocket.close();
        